package com.ctgu.server.controller;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ctgu.server.dao.entity.ArticleImage;
import com.ctgu.server.dao.vo.Result;
import com.ctgu.server.service.ArticleImageService;
import com.ctgu.server.utils.ResultUtil;
import com.ctgu.server.utils.oss.OssClientUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotEmpty;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ctgu
 * @since 2023-05-24
 */
@RestController
@RequestMapping("/server/articleImage")
@CrossOrigin
@Api(tags = "文章图片操作接口")
public class ArticleImageController {
    @Autowired
    private ArticleImageService articleImageService;

    @PostMapping("/upload/articleImage")
    @ApiOperation(notes = "上传图片",value = "上传文章图片")
    public Result uploadArticleImage(@NotEmpty @RequestParam Long articleId,@NotEmpty @RequestParam String targetUrl, @RequestParam MultipartFile multipartFile){
        if(articleId==null||targetUrl==null){
            return ResultUtil.error("参数错误！"+articleId+" "+targetUrl);
        }
        return  articleImageService.uploadImage(articleId,targetUrl,multipartFile);
    }

    @PostMapping("/upload/image")
    @ApiOperation(notes = "上传图片",value = "上传图片")
    public Result uploadImage( @RequestParam MultipartFile multipartFile){
       if(multipartFile==null){
           return ResultUtil.error("未找到需上传实体！");
       }
       String url= OssClientUtils.upload(multipartFile);
       return ResultUtil.success("请求成功！",url);
    }

    @GetMapping("/upload/getList")
    @ApiOperation(notes = "获取轮播图数组",value = "getList")
    public Result getList(){
        List<ArticleImage> imageList= articleImageService.list();
        return ResultUtil.success(imageList);
    }

    @PutMapping("/update")
    @ApiOperation(notes = "修改图片",value = "update")
    public Result updateImage(ArticleImage articleImage){
        if(articleImage.getId()==null){
            return ResultUtil.error("id  为空");
        }
        LambdaUpdateWrapper<ArticleImage> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(ArticleImage::getArticleId,articleImage.getArticleId());
        boolean flag=  articleImageService.update(articleImage,lambdaUpdateWrapper);
        if(!flag){
            return ResultUtil.error("更新失败!请稍后再试！");
        }
        return ResultUtil.success("修改成功");
    }


}

